package com.wx.dao.impl;

import com.wx.dao.PatientDao;
import com.wx.domain.Patient;
import com.wx.utils.JDBCUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @author 27250
 */

public class PatientDaoImpl implements PatientDao {
    public JdbcTemplate jdbcTemplate= new JdbcTemplate(JDBCUtils.getDataSource());
    @Override
    public Patient findByUsername(String username) {
        Patient patient=null;
        try{
            patient=jdbcTemplate.queryForObject("select * from patient where username = ?",new BeanPropertyRowMapper<Patient>(Patient.class),username);
        }catch (Exception e){
            return null;
        }
        return patient;
    }

    @Override
    public void modifyPassword(String username, String password) {
        jdbcTemplate.update("update patient set password = ? where username = ?",password,username);
    }

    @Override
    public double getWalletById(String patientId) {
        return jdbcTemplate.queryForObject("select wallet from patient where patientId = ?",
                Integer.class,patientId);
    }

    @Override
    public void paymentMoney(double wallet, String patientId) {
        jdbcTemplate.update("update patient set wallet = ? where patientId = ?",wallet,patientId);
    }

    @Override
    public int add(Patient patient) {
        PreparedStatementCreator creator=new PreparedStatementCreator() {
            @Override
            public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
                PreparedStatement preparedStatement=connection.prepareStatement("insert into `patient` values(?,?,?,?,?,?)",PreparedStatement.RETURN_GENERATED_KEYS);
                preparedStatement.setObject(1,null);
                preparedStatement.setString(2, patient.getPatientName());
                preparedStatement.setString(3,"");
                preparedStatement.setDouble(4,0);
                preparedStatement.setString(5,patient.getUsername());
                preparedStatement.setString(6,patient.getPassword());
                return preparedStatement;
            }
        };

        GeneratedKeyHolder keyHolder=new GeneratedKeyHolder();

        jdbcTemplate.update(creator, keyHolder);

        //        jdbcTemplate.update("insert into sys_user values (null,?,?,?,?)",user.getUsername(),user.getEmail(),user.getPassword(),user.getPhoneNum());
        return Objects.requireNonNull(keyHolder.getKey()).intValue();
    }
}
